// 管理用户数据相关
import {defineStore} from 'pinia'
import {ref} from 'vue'
import {loginApi, logoutApi} from '@/apis/login.js'
import instance from "@/utils/axios_config.js";

export const useUserStore = defineStore('userInfo', () => {
    // 1. 定义管理用户数据的state
        const userInfo = ref({
            username: '',
            nickname: '',
            avatar: '',
        })
    // 2. 定义获取接口数据的action函数
    const getUserInfo = async ({username, password}) => {
        const res = await loginApi({username, password})
        // 往localStore中存储用户信息
        userInfo.username = res.data.map.username
        userInfo.nickname = res.data.map.nickname
        userInfo.avatar = res.data.map.avatar
        console.log("存储的用户数据")
        console.log(userInfo)
        console.log("登录返回信息")
        console.log(res)
        //     往localStore存储token
        localStorage.setItem('accessToken', res.data.map.accessToken)
        localStorage.setItem('refreshToken', res.data.map.refreshToken)
    }

        // 获取用户名和头像
        const getNowUserInfo = () => {
            let nowUserInfo = {}
            nowUserInfo.username = userInfo.username
            nowUserInfo.nickname = userInfo.nickname
            nowUserInfo.avatar = userInfo.avatar
            return nowUserInfo
    }

    // 退出时清除用户信息
    const clearUserInfo = () => {
        userInfo.value = {}
    }
        // 退出登录
        const logout = () => {
            logoutApi().then(res => {
                console.log("退出登录")
                console.log(res)
                if (res.data.code === 1) clearUserInfo()

            }).catch(err => {
                console.log(err)
                ElMessage({
                    type: 'error',
                    message: '退出失败'
                })
            })
            clearUserInfo()
        }
        //获取access_token
        const getAccessToken = () => {
            return userInfo.value.accessToken
        }
        //获取refresh_token
        const getRefreshToken = () => {
            return userInfo.value.refreshToken
        }
        //更新token
        const updateToken = (accessToken, refreshToken) => {
            userInfo.value.accessToken = accessToken
            userInfo.value.refreshToken = refreshToken
    }
    // 3. 以对象的格式把state和action return
    return {
        getUserInfo,
        clearUserInfo,
        getNowUserInfo,
        logout
    }
    },
    {
    persist: true,
})